package com.commodity.servlet;

import com.commodity.Service.UserService;
import com.commodity.Service.userServiceImp.UserServiceImp;
import com.commodity.common.LoginFilter;
import com.commodity.entity.User;
import com.commodity.utils.BeanFactory;
import com.commodity.utils.Md5Utils;
import com.mysql.cj.Session;
import com.wf.captcha.utils.CaptchaUtil;
import org.springframework.util.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/user/*")
public class UserServlet extends HttpServlet {
    private final UserService userService = BeanFactory.getInstance(UserServiceImp.class);
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String action = req.getPathInfo();
        String method = req.getMethod().toLowerCase();
        if ("/login".equals(action)) {
            if ("get".equals(method)) {
                String error = (String) req.getSession().getAttribute("error");

                User user = (User) req.getSession().getAttribute("User");
                if (user==null){
                    user = (User) req.getAttribute("User");
                }
                req.setAttribute("User",user);
                req.getSession().removeAttribute(LoginFilter.LOGIN_KEY);
                if (StringUtils.hasText(error)) {
                    req.setAttribute("error", error);
                    req.getSession().removeAttribute("error");
                }
                System.out.println(action+""+method);
                req.getRequestDispatcher("/WEB-INF/jsp/login/login.jsp").forward(req, resp);

            } else {
                doLogin(req, resp);
            }
        } else if ("/logout".equals(action)) {
            System.out.println(action);
            req.getSession().removeAttribute(LoginFilter.LOGIN_KEY);
            resp.sendRedirect(req.getContextPath());
        } else if ("/captcha".equals(action)){
            CaptchaUtil.out(170,30,4,req,resp);
        }else if ("/editPwd".equals(action)){
            if ("get".equalsIgnoreCase(method)){
                User user = (User) req.getSession().getAttribute(LoginFilter.LOGIN_KEY);
                String success = (String) req.getSession().getAttribute("success");
                String error = (String) req.getSession().getAttribute("error");
                if (StringUtils.hasText(error)){
                    req.setAttribute("error",error);
                    req.getSession().removeAttribute("error");
                    req.getRequestDispatcher("/WEB-INF/jsp/index/editPwd.jsp").forward(req,resp);
                }else if (StringUtils.hasText(success)){
                    req.setAttribute("success","success");
                    req.getSession().removeAttribute("success");
                    req.getRequestDispatcher("/WEB-INF/jsp/index/editPwd.jsp").forward(req,resp);
                }else {
                    req.setAttribute("User",user);
                    req.getRequestDispatcher("/WEB-INF/jsp/index/editPwd.jsp").forward(req, resp);
                }

            }else{
                editPwd(req,resp);
            }
        }
    }



    private void doLogin(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String captcha = req.getParameter("captcha");
        String correct = (String) req.getSession().getAttribute("captcha");
        User dbUser = userService.findByUserName(username);
        if (!correct.equalsIgnoreCase(captcha)){
            req.getSession().setAttribute("error","验证码不正确");
            resp.sendRedirect(req.getContextPath()+"/user/login");
            User user1 = new User();
            user1.setUsername(username);
            user1.setPassword(password);
            req.getSession().setAttribute("User",user1);
            return;
        }

        if (dbUser == null) {
            req.getSession().setAttribute("error", "用户不存在");
            resp.sendRedirect(req.getContextPath() + "/user/login");
            return;
        }
        String encrypted = Md5Utils.md5(password + "{" + username + "}");
        System.out.println(encrypted);
        if (encrypted.equals(dbUser.getPassword())) {
            User user = new User();
            user.setUsername(username);
            user.setPassword(password);
            req.getSession().setAttribute(LoginFilter.LOGIN_KEY,user);
            resp.sendRedirect(req.getContextPath()+"/index");
        }else{
            User user = new User();
            user.setUsername(username);
            req.setAttribute("User",user);
            req.getSession().setAttribute("error","密码不正确");
            resp.sendRedirect(req.getContextPath()+"/user/login");
        }

    }

    private void editPwd(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String oldPassword = req.getParameter("oldPassword");
        String newPassword = req.getParameter("newPassword");
        String newPassword1 = req.getParameter("newPassword1");
        User user = (User) req.getSession().getAttribute(LoginFilter.LOGIN_KEY);
        String username = user.getUsername();
        String password = user.getPassword();
        HttpSession session = req.getSession();
        System.out.println("原账号"+username+"原密码"+password);
        System.out.println("新密码1"+newPassword+"新密码2"+newPassword1);
        String error = null;

        if (StringUtils.hasText(oldPassword)){
            if (!password.equals(oldPassword)){
                if (error==null){
                    error="原密码输入错误";
                }
            }
        } else if (!StringUtils.hasText(oldPassword)) {
            if (error==null){
                error = "原密码不允许为空";
            }
        }

        if (!StringUtils.hasText(newPassword)){
            if (error==null){
                error= "新密码不允许为空";
            }
        }
        if (newPassword.length()<5||newPassword.length()>12){
            if (error==null){
                error = "密码长度限制5~12位";
            }
        }
        if (!StringUtils.hasText(newPassword1)){
            if (error==null){
                error = "确认密码不允许为空";
            }
        }
        if (newPassword==null){
            newPassword="";
        }
        if (!newPassword.equals(newPassword1)){
            if (error==null){
                error="两次密码输入不一致";
            }
        }
        if (error!=null) {
            session.setAttribute("error", error);
            resp.sendRedirect(req.getContextPath() + "/user/editPwd");
            return;
        }
        boolean success = userService.editPwd(username,newPassword1);
        if (success){
            User user1 = new User();
            user1.setUsername(username);
            user1.setPassword(newPassword1);
            req.getSession().setAttribute(LoginFilter.LOGIN_KEY,user1);
            req.getSession().setAttribute("success","success");
            resp.sendRedirect(req.getContextPath() + "/user/editPwd");
        }else {
           session.setAttribute("error","修改失败,请联系管理员或稍后再试!");
           resp.sendRedirect(req.getContextPath()+"/user/list");
        }
    }
}
